// pages/address/address.js
import {getAllAddress,addAddress,deleteAddress,updateAddress} from "../../api/shippingAddress"
import {addressBehavior} from "./behavior"
import {setDefaultAddress} from '../../api/user'
import Dialog from '@vant/weapp/dialog/dialog';
import {toast} from "../../utils/extendApi"
import {setStorage} from "../../utils/storage"
Page({

  behaviors: [addressBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    deleteShow: false,
    title: "新增收货地址",
    collectionList: {},
    addressList: [
      // {
      //   consignee: '哈皮1',
      //   consigneephone: '19522222222',
      //   address: '哈皮路',
      //   isdefault: 1,
      // },{
      //   consignee: '哈皮2',
      //   consigneephone: '19522222222',
      //   address: '哈皮路',
      //   isdefault: 0,
      // },{
      //   consignee: '哈皮3',
      //   consigneephone: '19522222222',
      //   address: '哈皮路',
      //   isdefault: 0,
      // }
    ]
  },

  // 新增收货地址
  add() {
    this.setData({
      show: true,
      title: "新增收货地址",
      collectionList: {}
    })
  },

  // 修改收货地址
  update(event) {
    const {index} = event.currentTarget.dataset
    const obj = JSON.parse(JSON.stringify(this.data.addressList[index]))
    this.setData({
      show: true,
      title: '修改收货地址',
      collectionList: obj
    })
  },

  close(event) {
    const {detail} = event
    const {address, consignee, consigneephone} = this.data.collectionList
    // 如果当前点击确定
    if (detail === 'confirm') {
      if (!address || !consignee || !consigneephone) {
        toast({title: '地址信息不全！',icon: 'error'})
        return;
      }
      this.data.collectionList.userid = this.data.userInfo.id
      // 新增逻辑
      if (this.data.title === '新增收货地址') {
        addAddress(this.data.collectionList).then(({data}) => {
          if (data) {
            this.findAllAddress()
            toast({title: '新增地址成功！', icon: 'success'})
          }else {
            toast({title: '新增地址失败！', icon: 'error'})
          }
        })
      }else {
        if (!address || !consignee || !consigneephone) {
          toast({title: '地址信息不全！',icon: 'error'})
          return;
        }
        // 修改逻辑
        updateAddress(this.data.collectionList).then(({data}) => {
          if (data) {
            this.findAllAddress()
            toast({title: '修改地址成功！', icon: 'success'})
          }else {
            toast({title: '修改地址失败！', icon: 'error'})
          }
        })
      }
    }
    this.setData({
      show: false
    })
  },

  async deleteClose(event) {
    // console.log(event);
    if (event.detail === 'confirm') {
      const {data} = await deleteAddress(this.data.collectionList.id)
      if (data) {
        this.findAllAddress()
        toast({title: '删除成功！',icon: 'success'})
      }else {
        toast({title: '删除失败！',icon: 'error'})
      }
    }
    this.setData({
      deleteShow: false
    })
  },

  delete(event) {
    const {index} = event.currentTarget.dataset
    const obj = JSON.parse(JSON.stringify(this.data.addressList[index]))
    this.setData({
      deleteShow: true,
      collectionList: obj
    })
  },

  async findAllAddress() {
    const {data: addressList} = await getAllAddress(this.data.userInfo.id)
    this.setData({
      addressList
    })
  },

  inputchange(event){
    // console.log(event);
    const {name} = event.currentTarget.dataset
    const {detail} = event
    this.setData({
      [`collectionList.${name}`]: detail
    })
  },
  // 选择送货地址（针对商品送达地址）
  toSelectPath(event) {
    this.changeAddressObj(this.data.addressList[event.currentTarget.dataset.index])
    // 设置默认地址，下次同一个用户就不需要再次选择地址了
    setDefaultAddress(this.data.addressList[event.currentTarget.dataset.index]).then((res) => {
      const userInfoObj = JSON.parse(JSON.stringify(this.data.userInfo))
      userInfoObj.defaultshippingaddress = this.data.addressList[event.currentTarget.dataset.index]
      setStorage("userInfo", userInfoObj)
      this.setUserInfo(userInfoObj)
    })
    wx.navigateTo({
      url: '/pages/selectPath/selectPath?isSend=true',
    })
  },

  onLoad() {
    this.findAllAddress()
  }
})